package de.tabuma.pm.security;

import de.tabuma.adminarea.*;
import java.util.*;
import java.util.logging.*;
import de.tabuma.lib.contentmanagement.*;

import de.tabuma.pm.logik.*;
import de.tabuma.ssoclient.logik.*;
import de.tabuma.ssoclient.entity.*;

/**
 * @author $Author: alefen $
 * @version $Revision: 1.1.1.1.6.1 $
 * @since $Date: 2010/01/13 10:19:20 $
 */
public class SecurityProviderInstanceFacade implements FacadeInterface {
    private static final Logger log = Logger.getLogger(SecurityProviderInstanceFacade.class.getName());


    public static String getSingleSignOnId(int id) {
        SecurityProviderInstance spi = get_standard(id);
        if(spi.getSecurityProviderUrl().equals("")) {
            try {
                String ssoId = SSOFacade.getSSO(spi.getManagementUsername(), spi.getManagementPassword());
                return ssoId;
            }
            catch(Exception e) {
                    String warning = e.getMessage()+"/"+e.getCause()+"/"+e.getClass()+"\n";
                for(int i=0;i<e.getStackTrace().length;i++) {
                    warning += e.getStackTrace()[i]+"\n";
                }
                log.severe(warning);
            }
        }
        return null;
    }

    private static String createPassword() {
        char character[] = {'a','b','c','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};
        int length = (int)(Math.random()*30)+20;
        String ssoId = "";
        for(int i=0;i<length;i++) {
            int index = (int) (Math.random()*character.length);
            ssoId += character[index];
        }
        return ssoId;
    }

    private static SecurityProviderInstance getSecurityProviderInstanceFromTabumaSso(SecurityProviderInstance securityProvider, String googleuser) {
        int id = -1;

        List<AdminSetting> usernameList = AdminSettingFacade.getList(de.tabuma.pm.constants.TABUMA_SSO_STANDARD_USERNAME);
        List<AdminSetting> passwordList = AdminSettingFacade.getList(de.tabuma.pm.constants.TABUMA_SSO_STANDARD_PASSWORD);
        
        boolean out = false;
        if(usernameList.size()<1) {
            log.severe("Tabuma SSO Standard Username is not set.");
            out = true;
        }
        if(passwordList.size()<1) {
            log.severe("Tabuma SSO Standard Password is not set.");
            out = true;
        }
        if(out) return null;

        String username = usernameList.get(0).getValue();
        String password = passwordList.get(0).getValue();
        
        try {

            String ssoId = SSOFacade.getSSO(username, password);

            String customerName = de.tabuma.pm.project.logik.ProjectFacade.get(securityProvider.getProjectId()).getName();
            Customer customer = new Customer();
            customer.setName("tabuma customer / " + customerName);
            int customerId = CustomerFacade.create1(customer, ssoId, googleuser);

            Group group = new Group();
            group.setAdminCustomer(true);
            group.setAdminGroup(true);
            group.setAdminProject(true);
            group.setAdminUser(true);
            group.setCustomerId(customerId);
            group.setName("Tabuma group "+customerName);
            group.setNoLicenseNeeded(true);
            int groupid = GroupFacade.create(group, ssoId);

            Project project = new Project();
            project.setCustomerId(customerId);
            project.setName("Tabuma Platform Project "+securityProvider.getProjectId());
            int ssoProjectId = ProjectFacade.create(project, ssoId);

            User user = new User();
            user.setName("tabumaplattform.project"+ssoProjectId);
            user.setPassword(createPassword());
            int userId = UserFacade.create(user, ssoId, googleuser);

            UserGroup ug = new UserGroup();
            ug.setGroupId(groupid);
            ug.setUserId(userId);
            UserGroupFacade.create(ug, ssoId);

            id = ssoProjectId;
            
            securityProvider.setManagementUsername(user.getName());
            securityProvider.setManagementPassword(user.getPassword());
            securityProvider.setSsoProjectId(ssoProjectId);
            log.warning("ssoProjectId:"+ssoProjectId);

            return securityProvider;

        }
        catch(Exception e) {
            String warning = e.getMessage()+"/"+e.getCause()+"/"+e.getClass()+"\n";
                for(int i=0;i<e.getStackTrace().length;i++) {
                    warning += e.getStackTrace()[i]+"\n";
                }
                log.warning(warning);
        }

        return null;
    }

    private static void unactivateList(int projectId, String user) {
        List<SecurityProviderInstance> spList = getList(projectId);
        for(int i=0;i<spList.size();i++) {
            SecurityProviderInstance spi = spList.get(i);
            spi.activ = new Boolean(Boolean.FALSE);
            standard_update(spi, user);
        }
    }

    public static int create(SecurityProviderInstance securityProvider, String user) {
        if(securityProvider.activ.booleanValue()) {
            unactivateList(securityProvider.projectId, user);
        }
        if(securityProvider.securityProviderUrl.equals("")) {
            securityProvider = getSecurityProviderInstanceFromTabumaSso(securityProvider, user);
        }
        return (int) PMF.doCreate(securityProvider, user);
    }

    public int createElement(Object object, String user) {
        return create((SecurityProviderInstance) object, user);
    }

    public static void update(SecurityProviderInstance securityProvider, String user) {
        if(securityProvider.activ.booleanValue()) {
            unactivateList(securityProvider.projectId, user);
        }
        standard_update(securityProvider, user);
    }

    public static void standard_update(SecurityProviderInstance securityProvider, String user) {
        int id = securityProvider.getId().intValue();
        SecurityProviderInstance spi = get(id);
        if(spi.getSecurityProviderUrl().equals("")) {
            securityProvider.securityProviderUrl = spi.securityProviderUrl;
            securityProvider.managementPassword = spi.managementPassword;
            securityProvider.managementUsername = spi.managementUsername;
            securityProvider.ssoProjectId = spi.ssoProjectId;
        }
        PMF.doUpdate(securityProvider, user);
    }

    public void updateElement(Object object, String user) {
        update((SecurityProviderInstance) object, user);
    }

    public static SecurityProviderInstance get(int id) {
        SecurityProviderInstance spi = get_standard(id);
        if(spi.getSecurityProviderUrl().equals("")) {}
        return spi;
    }

    public static SecurityProviderInstance get_standard(int id) {
        return PMF.get(id, new SecurityProviderInstance());
    }

    public SecurityProviderInstance getElement(int id) {
        return get(id);
    }

    public static void remove(int id, String user) {
        SecurityProviderInstance securityProvider = get(id);
        PMF.doRemove(securityProvider, user);
    }

    public void removeElement(int id, String user) {
        remove(id, user);
    }

    public static List<SecurityProviderInstance> getList(int projectId) {
        String keys[] = {"projectId"};
        String values[] = {""+projectId};
        return PMF.get(keys, values, new SecurityProviderInstance());
    }

    public List getElementList(String listParameter) {
        Integer intValue = Integer.valueOf(listParameter);
        return getList(intValue);
    }

}
